//
//  UIColor+Extension.swift
//  七哥直播
//
//  Created by seven on 2017/11/9.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit

extension UIColor{
    //在extension中给系统方法扩充构造函数，只能扩充‘便利构造函数’
    convenience init(R: CGFloat, G: CGFloat, B: CGFloat, alpha: CGFloat = 1.0){
        self.init(red: R/255.0, green: G/255.0, blue: B/255.0, alpha: alpha)
    }
    
    convenience init?(hex: String){
        // 0xFF0000
        // 1.判断字符串长度是否符合
        guard hex.count >= 6 else {
            return nil
        }
        // 2.将字符串转成大写
        var tempHex = hex.uppercased()
        // 3.判断开头: 0x/#/##
        if tempHex.hasPrefix("0x") || tempHex.hasPrefix("##"){
            tempHex = (tempHex as NSString).substring(from: 2)
        }
        if tempHex.hasPrefix("#"){
            tempHex = (tempHex as NSString).substring(from: 1)
        }
        // 4.分别取出RGB
        var range = NSRange(location: 0, length: 2)
        let rHex = (tempHex as NSString).substring(with: range)
        range.location = 2
        let gHex = (tempHex as NSString).substring(with: range)
        range.location = 4
        let bHex = (tempHex as NSString).substring(with: range)
        
        // 5.将16进制转换成 emoji表情
        var r: UInt32 = 0, g: UInt32 = 0, b: UInt32 = 0
        Scanner(string: rHex).scanHexInt32(&r)
        Scanner(string: gHex).scanHexInt32(&g)
        Scanner(string: bHex).scanHexInt32(&b)
        self.init(R: CGFloat(r), G: CGFloat(g), B: CGFloat(b))
    }
    
    // 随机色
    class func randomColor() -> UIColor {
        return UIColor(R: CGFloat(arc4random_uniform(256)), G: CGFloat(arc4random_uniform(256)), B: CGFloat(arc4random_uniform(256)))
    }
    
    // 获取RGB差值
    class func getRGBDelta(firstColor: UIColor, secondColor: UIColor) -> (CGFloat,CGFloat,CGFloat){
        let firstRGB = firstColor.getRGB()
        let secondRGB = secondColor.getRGB()
        return (firstRGB.0 - secondRGB.0,firstRGB.1 - secondRGB.1,firstRGB.2 - secondRGB.2)
    }
    
    func getRGB() -> (CGFloat,CGFloat,CGFloat){
        guard let cpms = cgColor.components else {
            fatalError("保证颜色以RGB方式传入")
        }
        return (cpms[0]*255,cpms[1]*255,cpms[2]*255)
    }
}
